<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/18
 * Time: 12:45
 */

namespace backend\modules\qywx\controllers;

use backend\modules\qywx\QywxAuthHandler;
use common\business\qywx\QywxUserApiHandler;
use common\business\QywxApiService;
use common\consts\CommonResources;
use common\helpers\StringUtil;
use common\models\Log;
use common\models\User;
use yii;
use yii\web\Controller;
use yii\helpers\Json;

class AuthController extends Controller
{
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'auth' => [
                'class' => 'yii\authclient\AuthAction',
                'successCallback' => [$this, 'onAuthSuccess'],
            ]
        ];
    }

    /**
     * This function will be triggered when user is successfully authenticated using oAuth client.
     * 暂时没用到
     *
     * @param \yii\authclient\ClientInterface $client
     * @return boolean | \yii\web\Response
     */
//    public function onAuthSuccess($client)
//    {
////        见QywxAuth类
//        (new QywxAuthHandler($client))->handle();
//    }


    /**
     * @param $user User
     * @return string|yii\web\Response
     */
    protected function handleLogin($user){
        $apiHandler = new QywxUserApiHandler();
        if (Yii::$app->user->login($user)){
            $successMsg = CommonResources::ACTION_SUCCESS_MSG('Login', $user->username);
            $apiHandler->saveLog( new Log([
                'action' => $successMsg,
                'memo' => Json::encode($user->getAttributes()),
            ]));
            Yii::$app->getSession()->setFlash('success', $successMsg);
            return $this->goBack();
        }
        else {
            $errMsg = CommonResources::ACTION_FAIL_MSG('Login', 'User', $user->username);
            $apiHandler->saveLog( new Log([
                'action' => $errMsg,
                'memo' => Json::encode($user->getAttributes()),
            ]));
            Yii::$app->getSession()->setFlash('error', $errMsg);
            return $this->render('login');
        }
    }

    /**
     * eg: http://www.gzkr945.com/qywx/auth/auth-finish?code=8Ax36fkiTa2uI9t8YC8xhtlHPTYZ--mEYOWt7f7IPK8&state=web_login@gyoss9&appid=wxd11fdf2cc211b34a
     * @param $code
     * @param $state
     * @param $appid
     * @return string|yii\web\Response
     */
    public function actionAuthFinish($code, $state, $appid){
        $apiHandler = new QywxUserApiHandler();
        $qywx_user = $apiHandler->getInfoByCode($code);

        if (!$qywx_user){
            $errMsg = CommonResources::ACTION_NAME_MODEL_FAIL('Get', 'User', $code);
            $apiHandler->saveLog( new Log([
                'action' => CommonResources::ACTION_MSG('Get', 'User'),
                'memo' => $errMsg,
            ]));
            Yii::$app->getSession()->setFlash('error', $errMsg);
            return $this->render('login');
        }
        else {
            $user = User::findOne([
                'email' => $qywx_user->email,
            ]);
            if ($user) { // 登录
                // 更新用户资料
                $user->setAttribute('fullname', $qywx_user->name);
                $user->setAttribute('avatar', $qywx_user->avatar);
                $user->setAttribute('position', $qywx_user->position);
                $user->setAttribute('mobile', $qywx_user->mobile);
                if($apiHandler->saveRecordUnsafe($user)){
                    return $this->handleLogin($user);
                }
                else {
                    $errMsg = CommonResources::ACTION_FAIL_MSG('Save', 'User', $user->username);
                    $apiHandler->saveLog( new Log([
                        'action' => $errMsg,
                        'memo' => Json::encode($user->getAttributes()),
                    ]));
                    Yii::$app->getSession()->setFlash('error', $errMsg);
                    return $this->render('login');
                }
            } else { // 注册新用户
                if (!StringUtil::isNullOrWhiteSpace($qywx_user->email)) {
                    $user = new User([
                        'username' => $qywx_user->userid,
                        'fullname' => $qywx_user->name,
                        'email' => $qywx_user->email,
                        'password_hash' => md5($qywx_user->email . rand() . time()),
                        'avatar' => $qywx_user->avatar,
                        'position' => $qywx_user->position,
                        'mobile' =>$qywx_user->mobile,
                        'auth_key' => md5($qywx_user->email . rand() . time()),
                        'created_at' => time(),
                        'updated_at' => time(),
                    ]);
                    if($apiHandler->saveRecordUnsafe($user)){
                        return $this->handleLogin($user);
                    }
                    else {
                        $errMsg = CommonResources::ACTION_FAIL_MSG('Save', 'User', $user->username);
                        $apiHandler->saveLog( new Log([
                            'action' => $errMsg,
                            'memo' => Json::encode($user->getAttributes()),
                        ]));
                        Yii::$app->getSession()->setFlash('error', $errMsg);
                        return $this->render('login');
                    }
                } else {
                    $errMsg = CommonResources::ACTION_FAIL_MSG('Register', 'User', $user->username);
                    $apiHandler->saveLog( new Log([
                        'action' => $errMsg,
                        'memo' => Json::encode($user->getAttributes()),
                    ]));
                    Yii::$app->getSession()->setFlash('error', $errMsg);
                    return $this->render('login');
                }
            }
        }
    }
}